﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using ZdfFlatUI;
using Newtonsoft.Json.Linq;
using System.ComponentModel;

namespace NB_Controller_Test
{
    /// <summary>
    /// LogTimeLineWnd.xaml 的交互逻辑
    /// </summary>
    public partial class LogTimeLineWnd : Window
    {
        private ObservableCollection<Tuple<int, string, string>> list = new ObservableCollection<Tuple<int, string, string>>();

        

        public LogTimeLineWnd()
        {
            InitializeComponent();

            
            //for (int i = 0; i < 50; i++)
            //{
            //    //System.Threading.Thread.Sleep(1000);
            //    list.Add(new Tuple<int, string, string>(i % 5, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "哈哈哈哈"));
            //}

            for (int i = 0; i < 0; i++)
            {
                AddNewItem(E_EventType.Error, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "错误事件");
                AddNewItem(E_EventType.Warnning, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "警告事件");
                AddNewItem(E_EventType.Info, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "信息事件");
            }
            

            this.timeline.ItemsSource = list;
        }

        public void AddNewItem(E_EventType type, string strTime, string strInfo)
        {
            list.Add(new Tuple<int, string, string>(Convert.ToInt32(type), "[" + (list.Count + 1).ToString() + "] " + strTime, strInfo));
        }

        public void AddNewItemByEventLog(EventLog eventLog)
        {
            string strPredictTime = "[相对]";
            if(eventLog.bPredictTime == false)
                strPredictTime = "[绝对]";

            strPredictTime += (" [" + eventLog.byEventID.ToString() + "]");
            strPredictTime += (" [" + eventLog.usLogID.ToString() + "]");
            string strDateAndTime = "20" + eventLog.strDate + string.Format(" {0}:{1}:{2}", eventLog.byHour, eventLog.byMin, eventLog.bySecond);
            string strInfo = "{" + eventLog.strOriLogData + " -> " + eventLog.strHexOriLogData + "}\r\n" + eventLog.strAnalyData + "\r\n" + eventLog.strEventParamInfo;
            //list.Add(new Tuple<int, string, string>((Int32)eventLog.eventType, "[" + (list.Count + 1).ToString() + "] " + strDateAndTime + strPredictTime + " [" + eventLog.strEventIDInfo + "]", strInfo));
            //逆序插入
            list.Insert(0, new Tuple<int, string, string>((Int32)eventLog.eventType, "[" + (list.Count + 1).ToString() + "] " + strDateAndTime + strPredictTime + " [" + eventLog.strEventIDInfo + "]", strInfo));
        }

        private void add_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.Source as Button;
            switch (btn.Tag.ToString())
            {
                case "ReadWifiLog":
                    {
                        Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
                        openDlg.DefaultExt = ".txt";
                        openDlg.Filter = "Txt文档|*.txt|所有文件|*.*";
                        if (openDlg.ShowDialog() == true)
                        {
                            string strFilePath = openDlg.FileName;
                            string strAllText = System.IO.File.ReadAllText(strFilePath, Encoding.UTF8);

                            AnalysisWifiLogs(strAllText);
                        }
                    }
                    break;
                case "ReadPostmanLog":
                    AddNewItem(E_EventType.Info, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "信息事件[M]");
                    break;
                case "ReadJSon":
                    {
                        try
                        {
                            //获取到纯JSon数据
                            string strJsonTemp = "";
                            JObject jObj = JObject.Parse(strJsonTemp);
                            //除去多余无效\r\n以及空格
                            //strContentData = jObj.ToString();
                            strJsonTemp = jObj.ToString().Replace("\r\n ", "");
                            strJsonTemp = strJsonTemp.Replace("  ", "");
                            System.Diagnostics.Debug.WriteLine(strJsonTemp);

                            //构建Log
                            List<EventLog> eventLogs = EventLogManager.MakeEventLog(jObj);
                            foreach (EventLog eventLog in eventLogs)
                            {
                                //增加节点
                                AddNewItemByEventLog(eventLog);
                            }
                        }
                        catch (Newtonsoft.Json.JsonReaderException jsonEx)
                        {
                            string strError = jsonEx.Message;
                            //提取出有效信息，格式化为中文描述
                            string strTrueError = strError.Substring(strError.IndexOf("Path "));
                            string[] strLst = strTrueError.Split(',');

                            string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
                            string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
                            //ColmPos delete .
                            string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
                            strColmPos = strColmPos.TrimEnd('.');

                            strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

                            System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                            return;
                        }
                    }
                    break;
                case "RemoveAll":
                    list.Clear();
                    break;
                default:
                    break;
            }
        }

        private void AnalysisWifiLogs(string strLogs)
        {
            //string strSerializeJSON = System.IO.File.ReadAllText(@"D:\查询日志.txt", Encoding.UTF8);
            //EventLog dataBind = (EventLog)Newtonsoft.Json.JsonConvert.DeserializeObject(strSerializeJSON, typeof(EventLog));

            string strAllText = strLogs;
            //拆分
            string[] condition = { "ED ED " };
            //如果在拆分时不需要包含空字符串，则可以使用 StringSplitOptions.RemoveEmptyEntries 选项，例如在上例中将 StringSplitOptions.None 更改成 StringSplitOptions.RemoveEmptyEntries
            //string[] result = str.Split(condition, StringSplitOptions.None);

            string[] strJSonArray = strAllText.Split(condition, StringSplitOptions.None);
            try
            {
                foreach (string strJson in strJSonArray)
                {
                    int nStartIndex = strJson.IndexOf("{");
                    if (nStartIndex < 0)
                        continue;
                    //获取到纯JSon数据
                    string strJsonTemp = strJson.Substring(nStartIndex);
                    JObject jObj = JObject.Parse(strJsonTemp);
                    //除去多余无效\r\n以及空格
                    //strContentData = jObj.ToString();
                    strJsonTemp = jObj.ToString().Replace("\r\n ", "");
                    strJsonTemp = strJsonTemp.Replace("  ", "");
                    System.Diagnostics.Debug.WriteLine(strJsonTemp);

                    //构建Log
                    List<EventLog> eventLogs = EventLogManager.MakeEventLog(jObj);
                    foreach (EventLog eventLog in eventLogs)
                    {
                        //增加节点
                        AddNewItemByEventLog(eventLog);
                    }
                }
            }
            catch (Newtonsoft.Json.JsonReaderException jsonEx)
            {
                string strError = jsonEx.Message;
                //提取出有效信息，格式化为中文描述
                string strTrueError = strError.Substring(strError.IndexOf("Path "));
                string[] strLst = strTrueError.Split(',');

                string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
                string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
                //ColmPos delete .
                string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
                strColmPos = strColmPos.TrimEnd('.');

                strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

                System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                return;
            }
        }

        private void AnalysisPostmanLogs(string strLogs)
        {

        }
    }
}
